<template>
  <div>
    <el-card>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
        :model="ruleForm"
      >
        <el-form-item label="头像">
          <div class="el-upload" @click="openAvatar">
            <img
              v-if="ruleForm.avatar"
              :src="URL + '/' + ruleForm.avatar"
              style="width: 100px; height: 100px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input
            type="text"
            v-model="ruleForm.name"
            autocomplete="off"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item />
        <el-button
          type="primary"
          @click="$router.push('/personalCenter/changepassword')"
          >点击修改密码</el-button
        >
        <el-form-item style="margin-top: 30px">
          <el-button type="primary" @click="confirmUpdate">确认修改</el-button>
          <el-button @click="cancelUpdate">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog
      v-model="centerDialogVisible"
      title="添加"
      width="1000"
      align-center
      class="el-dialog"
    >
      <el-card style="max-width: 100%">
        <div class="btn">
          <el-upload
            class="avatar-uploader"
            :action="URL + '/admin/uploadpicture'"
            :show-file-list="false"
            name="picture"
            :data="{ type: 0 }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <el-button type="primary" size="large">单击上传</el-button>
          </el-upload>
        </div>
        <div class="bigbox">
          <div
            class="box"
            v-for="picture in pictures"
            :key="picture.id"
            @click="checkedPicture(picture)"
          >
            <img
              :src="URL + '/' + picture.img"
              style="width: 80px; height: 80px"
            />
            <!-- 选中 -->
            <div class="overspread" v-if="picture.id == checkedimgInfo.id">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
        <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="total"
          class="mt-4"
          :page-size="pageSize"
          @change="changePage"
          style="display: flex; justify-content: center"
        />
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmPicture">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const URL = import.meta.env.VITE_APP_API_URL;
import { reqGetPicture } from "@/api/picture/index";
import { reqGetPictureData } from "@/api/picture/model";
import UserAPI from "@/api/user/index";
import { useUserStore } from "@/store";
import { UploadProps } from "element-plus";
const userStore = useUserStore();
import { useRoute, useRouter } from "vue-router";
const $router = useRouter();
const $route = useRoute();
const centerDialogVisible = ref<boolean>(false);
const page = ref<number>(1);
const pageSize = ref<number>(32);
const type = ref<number>(3);
const total = ref<number>(0);
const pictures = ref<reqGetPictureData[]>([]);
const checkedimgInfo = ref({ id: 0, img: "" });
const ruleForm = ref({
  avatar: "",
  username: "",
  name: "",
});

// 添加图片
const openAvatar = () => {
  checkedimgInfo.value = { id: 0, img: "" };
  centerDialogVisible.value = true;
};

// 选中图片
const checkedPicture = (picture: any) => {
  checkedimgInfo.value = picture;
};

// 确定图片
const confirmPicture = () => {
  ruleForm.value.avatar = checkedimgInfo.value.img;
  centerDialogVisible.value = false;
};

// 分页
const changePage = (pageNum: number) => {
  page.value = pageNum;
  getPicture();
};

// 图片上传成功后
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  getPicture();
};

// 图片上传前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 取消修改信息
const cancelUpdate = () => {
  if (userStore.user.avatar && userStore.user.name && userStore.user.username) {
    ruleForm.value.avatar = userStore.user.avatar;
    ruleForm.value.name = userStore.user.name;
    ruleForm.value.username = userStore.user.username;
  }
};

// 确定修改信息
const confirmUpdate = () => {
  console.log(ruleForm.value);
  UserAPI.updatePersonalInfo(ruleForm.value);
  ElMessage({
    message: "修改成功",
    type: "success",
  });
  UserAPI.getInfo().then((data) => {
    Object.assign(userStore.user, { ...data });
  });
};

const getPicture = async () => {
  let result = await reqGetPicture({
    type: type.value,
    page: page.value,
    pageSize: pageSize.value,
  });
  total.value = result.count;
  pictures.value = result.rows;
};

onMounted(() => {
  getPicture();
  if (userStore.user.avatar && userStore.user.name && userStore.user.username) {
    ruleForm.value.name = userStore.user.name;
    ruleForm.value.username = userStore.user.username;
    ruleForm.value.avatar = userStore.user.avatar;
  }
  if ($route.query.checkedimg) {
    ruleForm.value.avatar = $route.query.checkedimg.toString();
  }
});
</script>

<style scoped lang="scss">
.el-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 1px dotted rgb(202 194 194);
}

.bigbox {
  display: flex;
  flex-wrap: wrap;

  .box {
    position: relative;
    margin: 10px 15px;

    .del {
      position: absolute;
      top: -8px;
      right: -8px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 18px;
      height: 18px;
      cursor: pointer;
      background-color: black;
      border-radius: 50%;

      span {
        color: white;
      }
    }

    .overspread {
      position: absolute;
      inset: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      color: #fff;
      // top: 0;
      // bottom: 0;
      // left: 0;
      // right: 0;
      background: rgb(0 0 0 / 40%);
    }
  }
}

.btn {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.el-dialog {
  height: 300px;
}
</style>
